package com.chenxys.algorithm.common;

/**
 * <p>
 *      leetcode 链表类题目公共类
 * </p>
 *
 * @author Chenxys
 * @version V1.0
 * @Package com.chenxys.algorithm.common
 * @date 12/30/23 3:18 PM
 * @Copyright ©
 */
@SuppressWarnings("all")
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    /**
     * <p>
     *     打印链表
     * </p>
     * @param head 待打印的链表
     */
    public static void printNode(ListNode head) {
        while (head != null) {
            System.out.print(head.val + "\t");
            head = head.next;
        }
    }

    /**
     * <p>
     *     获取链表长度
     * </p>
     * @param head 链表
     * @return 链表长度
     */
    public static Integer getNodeLength(ListNode head) {
        int size = 0;
        while (head != null) {
            size++;
            head = head.next;
        }
        return size;
    }

    /**
     * <p>
     *     生成随机长度链表
     * </p>
     * @param maxLen 最大长度
     * @param maxVal 最大值
     * @return 随机链表
     */
    public static ListNode generateListNode(int maxLen, int maxVal) {
        int len = (int) ((Math.random()) * (maxLen + 1));
        ListNode cur = new ListNode((int) ((Math.random()) * (maxVal + 1)));
        // ans 的作用就是抓住生成链表的头节点,否则返回的就是最后生成的一个节点
        ListNode ans = cur;
        for (int i = 0; i < len; i++) {
            cur.next = new ListNode((int) ((Math.random()) * (maxVal + 1)));
            cur = cur.next;
        }
        return ans;
    }

    /**
     * <p>
     *     判断两个链表是否一致
     * </p>
     * @param l1 链表1
     * @param l2 链表2
     * @return
     */
    public static boolean checkListNode(ListNode l1, ListNode l2) {
        while (l1 != null && l2 != null) {
            if (l1.val != l2.val) return false;
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;
    }
}
